
#include "webkit_message_handle.h"
#include "processhub.h"
#include "../activite/webcollector.h"

using namespace ProcessRouter;

void WebkitMessageHandle::didRecevied()
{
    CMessage msg = channel()->recv();
    if (!msg.isNull()) {
        ProcessRouter::MessagePackage package;
        if (!package.ParseFromString(msg.content())) {
            fprintf(stderr, "Failed to parse MessagePackage.\n");
            std::cout << __func__ <<  " | " << msg.content().size() << " : " << msg.content() << std::endl;
            _exit(-1);
        }

        if (package.has_request()) {
            ProcessRouter::RPCRequest request = package.request();
            //std::cout << __func__ << " : " << request.args() << std::endl;
            
            Json::Reader reader;
            Json::FastWriter writer;
            Json::Value value;

            if (!reader.parse(request.args(), value))
                return;
            value["clientid"] = request.clientid();

            std::string argJsonStr = writer.write(value);

            WebSpider *s = WebCollector::instance()->getSpider("spider webkit core");
            s->putRequestQueue(argJsonStr);
        } else if (package.has_commandkill()) {
            WebCollector::instance()->exitSelf();
        } else if (package.has_commandproxy()) {
            ProcessRouter::IPCCommandProxy command = package.commandproxy();
            std::string host = command.host();
            int port = command.port();

            WebCollector::instance()->setProxy("http", "", "", host.c_str(), port);
            WebCollector::instance()->enableProxy();
        }
    }
}

void WebkitMessageHandle::didConnected()
{
}

void WebkitMessageHandle::didError()
{
}

